// 成绩单数据解析器
class TranscriptParser {
  constructor() {
    this.studentInfo = {};
    this.courses = [];
    this.summary = {};
  }

  // 解析OCR识别结果
  parseOcrResult(ocrData) {
    try {
      console.log("开始解析OCR数据:", ocrData);

      // 验证输入数据
      if (!ocrData) {
        throw new Error("OCR数据为空");
      }

      if (typeof ocrData !== "object") {
        throw new Error("OCR数据格式错误");
      }

      const content = ocrData.content || "";
      const wordsInfo = ocrData.prism_wordsInfo || [];

      if (!content) {
        throw new Error("OCR内容为空");
      }

      console.log("OCR内容长度:", content.length);

      // 重置数据
      this.studentInfo = {};
      this.courses = [];
      this.summary = {};

      // 解析学生基本信息
      this.parseStudentInfo(content, wordsInfo);

      // 解析课程信息
      this.parseCourses(content, wordsInfo);

      // 解析汇总信息
      this.parseSummary(content, wordsInfo);

      const result = {
        student: this.studentInfo,
        courses: this.courses,
        summary: this.summary,
        imageUrl: ocrData.imageUrl,
        rawOcrData: ocrData,
      };

      console.log("解析结果:", result);
      return result;
    } catch (error) {
      console.error("解析成绩单数据失败:", error);
      throw new Error(`解析成绩单数据失败: ${error.message}`);
    }
  }

  // 解析学生基本信息
  parseStudentInfo(content, wordsInfo) {
    console.log("开始解析学生信息");

    // 从content中提取基本信息
    const studentIdMatch = content.match(/学号[：:]\s*(\d+)/);
    if (studentIdMatch) {
      this.studentInfo.studentId = studentIdMatch[1];
    }

    const nameMatch = content.match(/姓名[：:]\s*([^\s]+)/);
    if (nameMatch) {
      this.studentInfo.name = nameMatch[1];
    }

    const majorMatch = content.match(/专业[：:]\s*([^专业方向]+?)(?=\s|$)/);
    if (majorMatch) {
      this.studentInfo.major = majorMatch[1].trim();
    }

    const classMatch = content.match(/班级[：:]\s*([^\s]+)/);
    if (classMatch) {
      this.studentInfo.class = classMatch[1];
    }

    const collegeMatch = content.match(/学院[：:]\s*([^\s]+)/);
    if (collegeMatch) {
      this.studentInfo.college = collegeMatch[1];
    }

    console.log("学生信息:", this.studentInfo);
  }

  // 解析课程信息
  parseCourses(content, wordsInfo) {
    console.log("开始解析课程信息");

    // 使用简单的正则表达式从content中提取课程
    const courseLines = this.extractCourseLinesFromContent(content);
    console.log("提取的课程行:", courseLines);

    courseLines.forEach((line, index) => {
      const course = this.parseCourseLine(line);
      if (course && course.name && course.credits > 0) {
        this.courses.push(course);
      }
    });

    console.log("最终解析的课程:", this.courses);
  }

  // 从content中提取课程行
  extractCourseLinesFromContent(content) {
    console.log("开始提取课程行，内容长度:", content.length);
    console.log("原始内容:", content);

    const courseLines = [];
    let currentSemester = "未知学期";

    // 由于OCR文本可能被编码，我们需要更智能的解析
    // 先尝试按空格分割整个文本
    const words = content.split(/\s+/);
    console.log("分割后的词汇数量:", words.length);

    // 查找学期信息
    for (let i = 0; i < words.length; i++) {
      if (words[i].includes("学年第") && words[i].includes("学期")) {
        currentSemester = words[i];
        console.log("检测到学期:", currentSemester);
        break;
      }
    }

    // 使用更智能的解析方法
    // 查找课程模式：课程名 课程类型 数字 数字
    for (let i = 0; i < words.length - 3; i++) {
      const word1 = words[i];
      const word2 = words[i + 1];
      const word3 = words[i + 2];
      const word4 = words[i + 3];

      // 检查是否是课程模式（4个字段：课程名 课程类型 学分 成绩）
      if (
        this.isCourseType(word2) &&
        this.isNumber(word3) &&
        this.isNumber(word4)
      ) {
        const courseName = word1;
        const courseType = word2;
        let credits = parseFloat(word3);
        let score = parseFloat(word4);

        // 过滤掉过长的课程名（可能是标题）
        if (courseName.length > 50) {
          continue;
        }

        // 处理学分和成绩的格式问题
        if (credits > 100) {
          // 如果学分大于100，可能是成绩，交换位置
          const temp = credits;
          credits = score;
          score = temp;
        }

        // 处理小数点问题
        if (credits >= 10 && credits < 100) {
          credits = credits / 10;
        }
        if (score >= 1000) {
          score = score / 100;
        }

        const courseLine = `${courseName} ${courseType} ${credits} ${score} ${currentSemester}`;
        courseLines.push(courseLine);
        console.log("添加课程行(4字段):", courseLine);
      }
    }

    // 查找课程模式：课程名 课程类型 数字（3个字段）
    for (let i = 0; i < words.length - 2; i++) {
      const word1 = words[i];
      const word2 = words[i + 1];
      const word3 = words[i + 2];

      // 检查是否是课程模式（3个字段：课程名 课程类型 学分）
      if (this.isCourseType(word2) && this.isNumber(word3)) {
        const courseName = word1;
        const courseType = word2;
        let credits = parseFloat(word3);
        let score = 0; // 默认成绩为0

        // 过滤掉过长的课程名（可能是标题）
        if (courseName.length > 50) {
          continue;
        }

        // 处理学分格式问题
        if (credits >= 10 && credits < 100) {
          credits = credits / 10;
        }

        const courseLine = `${courseName} ${courseType} ${credits} ${score} ${currentSemester}`;
        courseLines.push(courseLine);
        console.log("添加课程行(3字段):", courseLine);
      }
    }

    // 去重和过滤
    const uniqueCourses = [];
    const seenCourses = new Set();

    for (const courseLine of courseLines) {
      const parts = courseLine.split(" ");
      const courseName = parts[0];

      // 过滤掉纯数字的课程名
      if (/^\d+\.?\d*$/.test(courseName)) {
        continue;
      }

      // 去重
      if (!seenCourses.has(courseName)) {
        seenCourses.add(courseName);
        uniqueCourses.push(courseLine);
      }
    }

    courseLines.length = 0;
    courseLines.push(...uniqueCourses);

    console.log("提取到课程行数量:", courseLines.length);
    return courseLines;
  }

  // 检查是否是课程类型
  isCourseType(word) {
    return (
      word.includes("专必") ||
      word.includes("专选") ||
      word.includes("公必") ||
      word.includes("公选") ||
      word === "专必" ||
      word === "专选" ||
      word === "公必" ||
      word === "公选" ||
      word.includes("涓撳繀") ||
      word.includes("涓撻") ||
      word.includes("鍏繀") ||
      word.includes("鍏") ||
      word === "涓撳繀" ||
      word === "涓撻" ||
      word === "鍏繀" ||
      word === "鍏"
    );
  }

  // 解码课程类型
  decodeCourseType(encodedType) {
    if (encodedType.includes("涓撳繀")) return "专必";
    if (encodedType.includes("涓撻")) return "专选";
    if (encodedType.includes("鍏繀")) return "公必";
    if (encodedType.includes("鍏")) return "公选";
    return encodedType;
  }

  // 解码课程名称
  decodeCourseName(encodedName) {
    // 这里可以添加更多的解码逻辑
    return encodedName;
  }

  // 检查是否是数字
  isNumber(word) {
    return /^\d+\.?\d*$/.test(word);
  }

  // 解析单行课程信息
  parseCourseLine(line) {
    // 按空格分割
    const parts = line.split(/\s+/).filter((part) => part.length > 0);

    let courseName = "";
    let courseType = "";
    let credits = 0;
    let score = 0;
    let semester = "未知学期";

    // 查找学期信息
    for (let i = 0; i < parts.length; i++) {
      if (parts[i].includes("学年第") && parts[i].includes("学期")) {
        semester = parts[i];
        break;
      }
    }

    // 如果没有找到学期，尝试从原始内容中查找
    if (semester === "未知学期") {
      const semesterMatch = line.match(/(\d{4}-\d{4}学年第[一二]学期)/);
      if (semesterMatch) {
        semester = semesterMatch[1];
      }
    }

    // 查找课程类型
    for (let i = 0; i < parts.length; i++) {
      if (this.isCourseType(parts[i])) {
        courseType = this.decodeCourseType(parts[i]);
        // 课程名称是类型前面的文本
        if (i > 0) {
          courseName = this.decodeCourseName(parts[i - 1]);
        }
        // 学分和成绩是类型后面的数字
        if (i + 1 < parts.length && this.isNumber(parts[i + 1])) {
          credits = parseFloat(parts[i + 1]);
        }
        if (i + 2 < parts.length && this.isNumber(parts[i + 2])) {
          score = parseFloat(parts[i + 2]);
        }
        break;
      }
    }

    return {
      name: courseName,
      type: courseType,
      credits: credits,
      score: score,
      semester: semester,
    };
  }

  // 解析汇总信息
  parseSummary(content, wordsInfo) {
    console.log("开始解析汇总信息");

    // 从content中提取汇总信息
    const gpaMatch = content.match(/历年平均学分绩点[：:]\s*(\d+\.\d+)/);
    if (gpaMatch) {
      this.summary.averageGPA = parseFloat(gpaMatch[1]);
    }

    const avgScoreMatch = content.match(/历年平均成绩[：:]\s*(\d+\.\d+)/);
    if (avgScoreMatch) {
      this.summary.averageScore = parseFloat(avgScoreMatch[1]);
    }

    const totalCreditsMatch = content.match(/毕业应取得总学分[：:]\s*(\d+)/);
    if (totalCreditsMatch) {
      this.summary.totalRequiredCredits = parseInt(totalCreditsMatch[1]);
    }

    const earnedCreditsMatch = content.match(/已获得总学分[：:]\s*(\d+\.\d+)/);
    if (earnedCreditsMatch) {
      this.summary.earnedCredits = parseFloat(earnedCreditsMatch[1]);
    }

    // 如果没有找到平均成绩，尝试从数字中提取
    if (!this.summary.averageScore) {
      const scoreMatch = content.match(/(\d+\.\d+)\s*4\.19/);
      if (scoreMatch) {
        this.summary.averageScore = parseFloat(scoreMatch[1]);
      }
    }

    // 如果没有找到平均学分绩点，尝试从数字中提取
    if (!this.summary.averageGPA) {
      const gpaMatch2 = content.match(/4\.19/);
      if (gpaMatch2) {
        this.summary.averageGPA = 4.19;
      }
    }

    // 计算总学分
    this.summary.totalCredits = this.courses.reduce(
      (total, course) => total + (course.credits || 0),
      0
    );

    // 计算总课程数
    this.summary.totalCourses = this.courses.length;

    console.log("汇总信息:", this.summary);
  }

  // 格式化显示数据
  formatForDisplay(parsedData) {
    return {
      student: parsedData.student,
      courses: parsedData.courses,
      summary: parsedData.summary,
      imageUrl: parsedData.imageUrl,
      rawOcrData: parsedData.rawOcrData,
    };
  }
}

module.exports = TranscriptParser;
